import os
import subprocess

TOP_LEVEL = None

def Full_Path(filename):
	global TOP_LEVEL
	if TOP_LEVEL is None:
		TOP_LEVEL = subprocess.check_output(
		["git", "rev-parse", "--show-toplevel"],
		stderr=subprocess.STDOUT).decode("utf-8").strip()
	return TOP_LEVEL + '/' + filename

def Check_UTF8(filename):
	filename = Full_Path(filename)
	try:
		subprocess.check_output(
			["iconv", "-f", "UTF-8", "-t", "UTF-8", filename],
			stderr=subprocess.DEVNULL)
		return True
	except subprocess.CalledProcessError:
		return False

def Check_UTF8_BOM(filename):
	filename = Full_Path(filename)
	with open(filename, "rb") as f:
		return True if f.read(3) == b'\xef\xbb\xbf' else False

# The maximum file-size for a file to be committed:
max_file_size = 512 # in KB (= 1024 byte)

"""
This function will return a human-readable filesize-string
 like "3.5 MB" for it's given 'num'-parameter.
From http://stackoverflow.com/questions/1094841
"""
def sizeof_fmt(num):
    for x in ['bytes','KB','MB','GB','TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0

def Check_File_Size(filename, max_file_size = max_file_size):
	filename = Full_Path(filename)
	stat = os.stat(filename)
	if stat.st_size > (max_file_size*1024):
		# File is to big, abort the commit:
		return False
	return True
